package com.smile.frame.workflow.flowable.demo.listener;

import com.google.common.collect.ImmutableSet;
import com.smile.frame.workflow.flowable.demo.constants.BpmConstants;
import com.smile.frame.workflow.flowable.demo.constants.BpmDeleteReasonEnum;
import com.smile.frame.workflow.flowable.demo.constants.BpmProcessInstanceStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableCancelledEvent;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 监听 {@link ProcessInstance} 的状态变更，更新其对应的 status 状态
 */
@Slf4j
@Component
public class BpmProcessInstanceEventListener extends AbstractFlowableEngineEventListener {


    @Resource
    private RuntimeService runtimeService;


    public static final Set<FlowableEngineEventType> PROCESS_INSTANCE_EVENTS = ImmutableSet.<FlowableEngineEventType>builder()
            .add(FlowableEngineEventType.PROCESS_CANCELLED)
            .add(FlowableEngineEventType.PROCESS_COMPLETED)
            .build();

    public BpmProcessInstanceEventListener() {
        super(PROCESS_INSTANCE_EVENTS);
    }

    @Override
    protected void processCancelled(FlowableCancelledEvent event) {
        log.info("流程实例监听，实例被取消start");
        // 1. 判断是否为 Reject 不通过。如果是，则不进行更新.
        // 因为，updateProcessInstanceReject 方法（审批不通过），已经进行更新了
        if (BpmDeleteReasonEnum.isRejectReason((String) event.getCause())) {
            return;
        }

        // 2. 更新流程实例 status
        runtimeService.setVariable(event.getProcessInstanceId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
                BpmProcessInstanceStatusEnum.CANCEL.getStatus());

//        // 3. 发送流程实例的状态事件
//        // 注意：此时如果去查询 ProcessInstance 的话，字段是不全的，所以去查询了 HistoricProcessInstance
//        HistoricProcessInstance processInstance = getHistoricProcessInstance(event.getProcessInstanceId());
//        // 发送流程实例的状态事件
//        processInstanceEventPublisher.sendProcessInstanceResultEvent(
//                BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.CANCEL.getStatus()));
        log.info("流程实例监听，实例被取消end");
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        log.info("流程实例监听，实例完成start");
        // 1. 更新流程实例 status
        runtimeService.setVariable(event.getProcessInstanceId(), BpmConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
                BpmProcessInstanceStatusEnum.APPROVE.getStatus());

//        // 2. 发送流程被【通过】的消息
//        messageService.sendMessageWhenProcessInstanceApprove(BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceApproveMessage(instance));
//
//        // 3. 发送流程实例的状态事件
//        // 注意：此时如果去查询 ProcessInstance 的话，字段是不全的，所以去查询了 HistoricProcessInstance
//        HistoricProcessInstance processInstance = getHistoricProcessInstance(instance.getId());
//        processInstanceEventPublisher.sendProcessInstanceResultEvent(
//                BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, processInstance, BpmProcessInstanceStatusEnum.APPROVE.getStatus()));
        log.info("流程实例监听，实例完成end");
    }

}
